<?php


namespace App\Http\Controllers\api;


use App\Http\Common\Author;
use App\Http\Common\Book;
use App\Http\Common\Chapter;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BookController extends Controller
{

//    书籍列表
    public function getBook(Request $request)
    {
        $type = (int)$request->input('type') ?? null;
        if($type == 0 || empty($type)){
            $where = $where = [['status','=',Book::$status]];//查询出来所有
        }else{
            $where = [['status','=',1],['sell_type','=',$type]];//按照条件
        }
        $data = Book::with('author','cate')->where($where)->get();
        return successMsg(objToArr($data));
    }

//    获取书籍详情
    public function getBookInfo(Request $request)
    {
        $book_id = (int)$request->input('book_id') ?? null;
        $book_info = Book::with('author','cate')->find($book_id);
        $data = objToArr($book_info);
        return successMsg($data);
    }

//    获取到作者信息
    public function getAuthorInfo(Request $request)
    {
        $book_id = (int)$request->input('book_id') ?? null;
        $book_info = Book::find($book_id);
        $author = Author::find($book_info->author_id);
        $data = objToArr($author);
        return successMsg($data);
    }

//    作者书籍
    public function getAuthorBook(Request $request)
    {
        $book_id = (int)$request->input('book_id') ?? null;
        $book_info = Book::where('status',Book::$status)->find($book_id);
        $book_list = Book::with('author')
            ->where('status',Book::$status)
            ->where('author_id',$book_info->author_id)
            ->get();
        $data = objToArr($book_list);
        return successMsg($data);
    }
//    书籍前10章
    public function getChapterList(Request $request)
    {
        $book_id = (int)$request->input('book_id') ?? null;
        $data = Chapter::where('book_id',$book_id)->limit(4)->get();
        $data = objToArr($data);
        $last_names = array_column($data,'index');
        array_multisort($last_names,SORT_DESC,$data);
        return successMsg($data);
    }
    //获取到这本书最新章节
    public function getNewChapterList(Request $request){
        $book_id = (int)$request->input('book_id') ?? null;
        $data = Chapter::where('book_id',$book_id)->orderByDesc('index')->first();
        $data = objToArr($data);
        return successMsg($data);
    }
    //轮播图接口
    public function banner()
    {
        $banner = DB::table("banner")->where('status',1)->get()->toArray();
        $data = objToArr($banner);
        return successMsg($data);
    }
}